package com.tsmti.doctor.controller;

import com.tsmti.shiro.web.filter.authc.FormAuthenticationFilter;
import com.tsmti.shiro.web.filter.authc.credential.RetryLimitHashedCredentialsMatcher;
import com.tsmti.system.entity.Organization;
import com.tsmti.system.entity.Principal;
import com.tsmti.system.service.OrganizationService;
import com.tsmti.system.service.UserService;
import com.tsmti.util.UserUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @Package：com.tsmti.system.controller
 * @Class：LoginController
 * @Description： TODO
 * @Author：zcw
 * @Date：Created in 2018/2/8 14:21
 * @Company:
 * @Version：
 * @Modified By:
 */
@Controller
@RequestMapping
public class LoginController {
    @Autowired
    private RetryLimitHashedCredentialsMatcher retryLimitHashedCredentialsMatcher;
    @Autowired
    private OrganizationService  organizationService;
    @Autowired
    private UserService userService;
    @RequestMapping(value = "/login")
    public ModelAndView login(HttpServletRequest request, HttpServletRequest response, Model model) {
        Principal principal = UserUtils.getPrincipal();
        // 如果已经登录，则跳转到管理首页
        if (principal != null && !principal.isMobileLogin()) {
            return new ModelAndView("redirect:/index");
        }
        String useruame = WebUtils.getCleanParam(request, FormAuthenticationFilter.DEFAULT_USERNAME_PARAM);
        String exception = (String) request.getAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME);
        // 是否开启验证码
        model.addAttribute("showCaptcha", "0");
        // 强制登陆跳转，重复认证异常加入验证码。
        if (ExcessiveAttemptsException.class.getName().equals(exception) || retryLimitHashedCredentialsMatcher.isForceLogin(useruame)) {
             model.addAttribute("showCaptcha", "1");
        }
        if (exception != null) {
            if (UnknownAccountException.class.getName().equals(exception)) {
                request.setAttribute("errorMsg", "用户名不存在");
            } else if (IncorrectCredentialsException.class.getName().equals(exception)) {
                request.setAttribute("errorMsg", "用户名/密码不正确");
            }else if(DisabledAccountException.class.getName().equals(exception)){
                request.setAttribute("errorMsg", "账号不允许登陆");
            }else {
                request.setAttribute("errorMsg", "系统错误");
            }
        }
        List<Organization> organizationList = organizationService.listByOrder("asc","id");
        ModelAndView view = new ModelAndView("login");
        view.addObject("organizationList",organizationList);
        return view;
    }

    @RequestMapping("/logout")
    public ModelAndView logout() {
        try {
            Subject subject = SecurityUtils.getSubject();
            if (subject != null && subject.isAuthenticated()) {
                subject.logout();
            }
            return new ModelAndView("/login");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ModelAndView("/index");
    }


}
